package com.example.demo.service;

import com.example.demo.entiy.Authority;
import com.example.demo.entiy.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service("userDetailsService")
/**
 * 创建一个实体类去实现UserDetailsService()接口
 * 目的:重写loadUserByUsername()方法 (必须这么做)
 */
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    @Autowired
    AuthorityService authorityService;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(s);
        List<Authority> authorityList = authorityService.getAuthorityListByUsername(s);


        List<SimpleGrantedAuthority> list =
                authorityList
                        //List集合(权限)变成字节流的形式
                        .stream()

                        .map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
                        .collect(Collectors.toList());
        if (user != null) {
            //把用户进行重新封装并返回 (用户姓名,密码.拥有的权限)
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), list);
            redisTemplate.opsForValue().set("user", user);
            return userDetails;
        }
        return null;
    }

}
